"""
3.训练

"""
from sklearn.neighbors import  KNeighborsClassifier
import pandas as pd

from LearnPy.MIClustering.MyBamic.bag_dist_matrix import bag_dist_matrix
from scipy.io import loadmat
import numpy as np
from LearnPy.MIClustering.MyBamic.bamic import bamic

def bartmip(musk,k,n_neighbors,dist_matrix,bag_center_dist):
    """

    :param musk: 用于训练的数据集
    :param k: 分簇的个数
    :param n_neighbors: knn中邻居的个数
    :param dist_matrix: 包与包的距离矩阵
    :param bag_center_dist: 包与簇中心的距离矩阵
    :return: 训练好的分类器
    """

    bag_num = len(musk['data'])
    #指定knn算法的邻居个数
    knn = KNeighborsClassifier(n_neighbors)

    #训练数据，测试数据
    train_data= bag_center_dist[:-1,:] # 训练数据


    # 求出训练目标，测试目标
    train_target = np.empty(bag_num)

    for i in range(0, bag_num):
        train_target[i] = musk["data"][i][1]


    # 训练
    knn.fit(train_data,train_target)

    return knn


def bartmip_test(musk,k,flag,n_neighbors):
    #包的个数
    bag_num = len(musk['data'])
    #用于训练时打乱包的顺序
    index = np.arange(bag_num)
    np.random.shuffle(index)

    # 包与包的距离矩阵
    dist_matrix = bag_dist_matrix(musk)
    # 包与簇中心的距离矩阵
    bag_center_dist = bamic(musk,k,dist_matrix)

    #指定knn算法的邻居个数
    knn = KNeighborsClassifier(n_neighbors)

    #训练数据，测试数据
    train_data, test_data = bag_center_dist[index[:bag_num - flag]], bag_center_dist[index[bag_num - flag:]]  # 训练数据，测试数据


    #求出训练目标，测试目标
    train_target = np.empty(bag_num - flag)
    test_target = np.empty(flag)
    for i in range(0,bag_num-flag):
        train_target[i] = musk["data"][index[i]][1]
    for i in range(0,flag):
        test_target[i] = musk["data"][index[i+bag_num-flag]][1]

    # 训练
    knn.fit(train_data,train_target)

    # 预测
    result = knn.predict(test_data)

    print("预测结果:",result)
    print("真实结果",test_target)
    print ("预测准确率：",(result==test_target).sum()/bag_num)
    return result



if __name__=="__main__":
    path = './musk1+.mat'
    musk = loadmat(path)
    #如果是自己测试的话就传什么musk就随便自己分一下，然后自己训练自己测试了
    bartmip_test(musk,14,10,3)

